using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace MTRC.ODMS.Web.SOM.CodeSetup
{
    /// <summary> 
    /// author:Zeng shunbo
    /// </summary>
    public partial class AssetItemEntry : BasePage_SOM
    {
        #region MenuID

        protected override string MenuID
        {
            get
            {
                return "M140803";
            }
        }

        #endregion

        #region Page Init And Load

        protected int DetailLength
        {
            get { return int.Parse(ViewState["DetailLength"].ToString()); }
            set { ViewState["DetailLength"] = value; }

        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.ChangeLanguage += new ChangeLanguageEventHandler(AssetItemEntry_ChangeLanguage);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.TracePageChange = true;

            if (!IsPostBack)
            {
                // add by Tim 20160613
                Session["Ismodify"] = false;
                Session["Index"] = null;
                //string tempName = "Qty0"+ ODMUserID;
                //Session["tempName"] = null;

                this.grdAssetItemHist.PageSize = this.GridViewPageDefaultSize();
                this.grdAssetItemDetail.PageSize = this.GridViewPageDefaultSize();

                this.btnVoid.Attributes.Add("onclick", "return confirm('" + GetMessage("COM_ConfirmSubmit") + "');");
                //this.btnSave.Attributes.Add("onclick", "return CheckEmpty('" + GetMessage("SOM_AssetItemEntryUpperNotNull") + "');");
                //this.btnSaveNew.Attributes.Add("onclick", "return CheckEmpty('" + GetMessage("SOM_AssetItemEntryUpperNotNull") + "');");
                //this.btnSaveReturn.Attributes.Add("onclick", "return CheckEmpty('" + GetMessage("SOM_AssetItemEntryUpperNotNull") + "');");
                DetailLength = int.Parse(MTRC.ODMS.DAL.CommonData.GetNumVal("SOM_DetailLength").ToString());
                SetLanguage();
                Display();
            }
            else
            {
                this.IsServerChanged = true;
            }
            /* Comment by jack 20151023 for U252 */
            ScriptManager.RegisterStartupScript(Page, typeof(string), "", "InitCombobox();", true);
        }

        #endregion

        #region Some private function

        private void Display()
        {
            if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "EDIT"
                && Request.QueryString["assetItemID"] != null)
            {
                BindStation();
                BindDetailList();
                BindHistoryList();

                FunctionItemSetting();

                int assetItemID = Convert.ToInt32(Request.QueryString["assetItemID"].ToString());
                Model.SOM.CodeSetup.CDAssetItemInfo assetItemInfo = BLL.SOM.CodeSetup.AssetItem.GetAssetItemInfoByID(assetItemID);
                txtAssetItem.Text = assetItemInfo.AssetitemCode;
                txtDescription.Text = assetItemInfo.AssetItemDesc;
                //this.ddlStation.SelectedValue = assetItemInfo.StationID.ToString();

                BindAssetType();
                //this.ddlAssetType.SelectedValue = assetItemInfo.AssetTypeID.ToString();

                FindByValueAndSelect(ddlAssetType, assetItemInfo.AssetTypeID.ToString());
                FindByValueAndSelect(ddlStation, assetItemInfo.StationID.ToString());

                this.chkObsolete.Checked = assetItemInfo.FlagObsolete;
                this.txtStockQty.Text = assetItemInfo.StockQty.ToString();

                this.txtAvailableQty.Text = assetItemInfo.AvailableQty.ToString();

                if (this.chkObsolete.Checked)
                {
                    VoidSetWhenDisplay();
                }

                EditSetting();
            }
            else if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "NEW")
            {
                FunctionItemSetting();
                BindAssetType();
                BindDetailList();
                BindHistoryList();
            }
            else
            {
                Response.Redirect("AssetItemList.aspx");
            }

            //if (this.chkItemSet.Checked)
            //{
            //    this.chkItemSet.Enabled = false;
            //    this.btnDetailNew.Enabled = true;
            //}
            //else
            //{
            //    this.btnDetailNew.Enabled = false;
            //}

            if (!this.chkItemSet.Checked)
            {
                this.btnDetailNew.Enabled = false;
            }
        }

        private void EditSetting()
        {
            int assetItemID = Convert.ToInt32(Request.QueryString["assetItemID"]);
            this.ddlStation.Enabled = false;

            if (this.grdAssetItemDetail.Rows.Count > 0)
            {
                this.chkItemSet.Checked = true;
                this.chkItemSet.Enabled = false;
            }

            if (BLL.SOM.CodeSetup.AssetItem.IsSubItem(assetItemID))
            {
                this.chkItemSet.Checked = false;
                this.chkItemSet.Enabled = false;
            }
        }

        private void NewSetting()
        {
            this.chkItemSet.Enabled = true;
        }

        //bind dropdownlist station.
        private void BindStation()
        {
            BindListControl(this.ddlStation, "LocationID", "Station", ODMS.DAL.SOM.CodeSetup.CDAssetType.GetStationList(LangCode), false);

            //update by gordon 20151020 U247
            //if (this.ddlStation.Items.FindByValue(this.ODMUser.StationID.ToString()) != null)
            //{
            //    this.ddlStation.SelectedValue = this.ODMUser.StationID.ToString();
            //}

            if (this.ddlStation.Items.FindByValue(this.ODMUser.LocationID.ToString()) != null)
            {
                this.ddlStation.SelectedValue = this.ODMUser.LocationID.ToString();
            }
        }

        private void BindAssetType()
        {
            int selectedStation = this.ddlStation.SelectedItem != null ? Convert.ToInt32(ddlStation.SelectedValue.ToString()) : 0;
            string stationIDs = selectedStation.ToString();

            //AssetTypeCode or AssetTypeDesc
            /*Comment by jack 20151023 for U252*/
            //BindListControl(this.ddlAssetType, "AssetTypeID", "AssetTypeCode", ODMS.DAL.SOM.CodeSetup.CDAssetType.GetAssetTypeList(stationIDs, "", true, this.LangCode), false);
            BindListControl(this.ddlAssetType, "AssetTypeID", "AssetTypeDesc", ODMS.DAL.SOM.CodeSetup.CDAssetType.GetAssetTypeList(stationIDs, "", true, this.LangCode), true,"");
        }

        //Get data table.
        private DataTable GetDataTable(string sessionKey)
        {
            int tempAssetItemID = -1;

            if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "EDIT")
            {
                if (Request.QueryString["assetItemID"] != null)
                {
                    tempAssetItemID = Convert.ToInt32(Request.QueryString["assetItemID"]);
                }
                else
                {
                    Response.Redirect("AssetItemList.aspx");
                }
            }

            if (ViewState[sessionKey] != null) //get Cache data or DB data.
            {
                return BLL.SOM.TempData.GetCacheData(Convert.ToInt32(ViewState[sessionKey])).Tables[0];
            }
            else if (sessionKey.ToUpper() == BLL.COM.Session.SOM_grdDetail.ToUpper())
            {
                return MTRC.ODMS.DAL.SOM.CodeSetup.CDAssetitemDtl.GetAssetItemDetail(tempAssetItemID, 0);
            }
            else if (sessionKey.ToUpper() == BLL.COM.Session.SOM_grdHist.ToUpper())
            {
                return MTRC.ODMS.DAL.SOM.CodeSetup.CDAssetitemHist.GetAssetItemHist(tempAssetItemID);//History table
            }
            else
            {
                return null;
            }
        }

        //Cache temp data.
        private void CacheTempData(DataTable dt, string sessionKey)
        {
            if (ViewState[sessionKey] != null)
            {
                //update temp data.
                BLL.SOM.TempData.UpdateCacheData(Convert.ToInt32(ViewState[sessionKey]), dt.DataSet);
            }
            else
            {
                ViewState[sessionKey] = ODMS.BLL.SOM.TempData.CacheDataSet(dt.DataSet, this.ODMUser.ID, this.ODMUser.Domain);
            }
        }

        //Get min value in column of dt.
        private int GetColumnMinValue(DataTable dt, string columnName)
        {
            int temp = 0;

            foreach (DataRow dr in dt.Rows)
            {
                if (dr[columnName].ToString().Trim().Length < 1)
                    continue;

                if (Convert.ToInt32(dr[columnName]) < temp)
                    temp = Convert.ToInt32(dr[columnName]);
            }

            return temp - 1;
        }

        //Get max value in column of dt.
        private int GetColumnMaxValue(DataTable dt, string columnName)
        {
            int temp = 0;

            foreach (DataRow dr in dt.Rows)
            {
                if (dr[columnName].ToString().Trim().Length < 1)
                    continue;

                if (Convert.ToInt32(dr[columnName]) > temp)
                    temp = Convert.ToInt32(dr[columnName]);
            }

            return temp + 1;
        }

        private void ClearAllText()
        {
            this.txtAssetItem.Text = "";
            this.txtAvailableQty.Text = "";
            this.txtDescription.Text = "";
            this.txtStockQty.Text = "";
        }

        /// <summary>
        /// Clear cache and session.
        /// </summary>
        private void ClearCache()
        {
            if (ViewState[BLL.COM.Session.SOM_grdDetail] != null)
                BLL.SOM.TempData.ClearCacheData(Convert.ToInt32(ViewState[BLL.COM.Session.SOM_grdDetail]));

            if (ViewState[BLL.COM.Session.SOM_grdHist] != null)
                BLL.SOM.TempData.ClearCacheData(Convert.ToInt32(ViewState[BLL.COM.Session.SOM_grdHist]));

            ViewState.Remove(BLL.COM.Session.SOM_grdDetail);
            ViewState.Remove(BLL.COM.Session.SOM_grdHist);
        }

        /// <summary>
        /// check is exist repert items in detail.
        /// </summary>
        /// <param name="assetType">assetType</param>
        /// <param name="srcAssetItemID">srcAssetItemID</param>
        /// <returns>b</returns>
        private bool CheckDetailRepertItems(int assetItemDtlID, int assetType, int srcAssetItemID)
        {
            DataTable dt = GetDataTable(BLL.COM.Session.SOM_grdDetail);
            bool bTemp = false;

            foreach (DataRow dr in dt.Rows)
            {
                if (Convert.ToInt32(dr["AssetItemDtlID"]) != assetItemDtlID && Convert.ToInt32(dr["SrcAssetItemID"]) == srcAssetItemID && Convert.ToInt32(dr["AssetTypeID"]) == assetType && !Convert.ToBoolean(dr["FlagObsolete"]))
                {
                    bTemp = true;

                    break;
                }
            }

            return bTemp;
        }

        /// <summary>
        /// Calculate StockQty and availableQty.
        /// </summary>
        private void CalculateStockQtyAndAvailableQty()
        {
            int stockQty = 0;
            DataTable histTable = GetDataTable(BLL.COM.Session.SOM_grdHist);

            foreach (DataRow dr in histTable.Rows)
            {
                if (!Convert.ToBoolean(dr["FlagObsolete"]))//not add void Qty.
                {
                    stockQty += dr["QtyChg"].ToString().Length > 0 ? Convert.ToInt32(dr["QtyChg"]) : 0;
                }
            }

            if (Request.QueryString["action"].ToUpper() == "EDIT")
            {
                this.txtAvailableQty.Text = "" + (stockQty - DAL.SOM.CodeSetup.CDAssetItem.GetAssetItemUsedSize(Convert.ToInt32(Request.QueryString["assetItemID"].ToString())));
            }
            else
            {
                this.txtAvailableQty.Text = stockQty.ToString();
            }

            this.txtStockQty.Text = stockQty.ToString();
        }

        //check all item not is null.
        private bool EmptyCheck()
        {
            bool ch = true;

            if (this.ddlStation.SelectedItem == null)
            {
                ch = false;

                PAlert("'" + this.lblStation.Text + "' " + GetMessage("SOM_NotIsEmpty", this.LangCode));

                return ch;
            }

            //if (this.ddlAssetType.SelectedItem == null) //Comment by jack 20151027 for U252
            if (this.ddlAssetType.SelectedItem == null || string.IsNullOrEmpty(this.ddlAssetType.SelectedItem.Value))
            {
                ch = false;

                PAlert("'" + this.lblAssetType.Text + "' " + GetMessage("SOM_NotIsEmpty", this.LangCode));

                return ch;
            }

            if (this.txtAssetItem.Text.Trim().Length < 1)
            {
                ch = false;

                PAlert("'" + this.lblAssetItem.Text + "' " + GetMessage("SOM_NotIsEmpty", this.LangCode));

                return ch;
            }

            if (this.txtDescription.Text.Trim().Length < 1)
            {
                ch = false;

                PAlert("'" + this.lblDescription.Text + "' " + GetMessage("SOM_NotIsEmpty", this.LangCode));

                return ch;
            }

            return ch;
        }

        /// <summary>
        /// Common save function and redirect other page.
        /// </summary>
        /// <param name="redirect">url</param>
        private void SaveFunction(string redirect)
        {
            if (EmptyCheck())
            {
                //update by gordon 20151019  U247
                //if (!DAL.SOM.Event.StationEventDa.IsLegalStation(this.ODMUser.StationID))
                if (!DAL.SOM.Event.StationEventDa.IsLegalStation(this.ODMUser.LocationID))
                {
                    //this.Alert("Current station is not an legal station for SOM");
                    this.Alert(this.GetMessage("SOM_LegalStationCheck"));
                }
                else
                {
                    DataTable detailTable = GetDataTable(BLL.COM.Session.SOM_grdDetail);
                    DataTable histTable = GetDataTable(BLL.COM.Session.SOM_grdHist);
                    Model.SOM.CodeSetup.CDAssetItemInfo assetItemInfo = new MTRC.ODMS.Model.SOM.CodeSetup.CDAssetItemInfo();

                    //create AssetItemInfo.
                    assetItemInfo.ActingasUser = ODMUser.ID;
                    assetItemInfo.AssetitemCode = this.txtAssetItem.Text;
                    assetItemInfo.AssetItemDesc = this.txtDescription.Text;
                    assetItemInfo.AssetTypeID = this.ddlAssetType.SelectedValue.Length > 0 ? Convert.ToInt32(ddlAssetType.SelectedValue) : -1;
                    assetItemInfo.AvailableQty = this.txtAvailableQty.Text.Trim().Length > 0 ? Convert.ToInt32(txtAvailableQty.Text) : 0;
                    assetItemInfo.StockQty = this.txtStockQty.Text.Trim().Length > 0 ? Convert.ToInt32(txtStockQty.Text) : 0;
                    assetItemInfo.CreateTime = DateTime.Now;
                    assetItemInfo.CreateUser = this.ODMUser.ID;
                    assetItemInfo.FlagObsolete = this.chkObsolete.Checked;
                    assetItemInfo.LastUpdTime = DateTime.Now;
                    assetItemInfo.LastUpdUser = this.ODMUser.ID;

                    //Check QueryString.
                    if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "EDIT")
                    {
                        if (Request.QueryString["assetItemID"] != null)
                        {
                            assetItemInfo.AssetItemID = Convert.ToInt32(Request.QueryString["assetItemID"]);
                        }
                        else
                        {
                            ClearCache();

                            Response.Redirect("AssetItemList.aspx");
                        }
                    }
                    else
                    {
                        assetItemInfo.AssetItemID = 0;
                    }


                    if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "NEW")
                    {
                        //Check existed.
                        if (!DAL.SOM.CodeSetup.CDAssetItem.CheckIsExist(assetItemInfo.AssetItemID, assetItemInfo.AssetTypeID, assetItemInfo.AssetitemCode))
                        {
                            int tempAssetItemID = BLL.SOM.CodeSetup.AssetItem.InsertAsetItem(histTable, detailTable, assetItemInfo);

                            ClearCache();

                            if (redirect.Length < 1)
                            {
                                redirect = "AssetItemEntry.aspx?action=EDIT&assetItemID=" + tempAssetItemID;

                                string addScript = "location.href='" + redirect + "'";
                                this.Alert(this.GetMessage("SaveSuccessfully"), 10, addScript);
                            }
                            else
                            {
                                string addScript = "location.href='" + redirect + "'";
                                this.Alert(this.GetMessage("SaveSuccessfully"), 10, addScript);
                            }
                        }
                        else
                        {
                            Alert(GetMessage("SOM_ExistSameItem"));
                        }
                    }
                    else if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "EDIT")
                    {
                        //Check existed.
                        if (!DAL.SOM.CodeSetup.CDAssetItem.CheckIsExist(assetItemInfo.AssetItemID, assetItemInfo.AssetTypeID, assetItemInfo.AssetitemCode))
                        {
                            BLL.SOM.CodeSetup.AssetItem.UpdateAssetItem(histTable, detailTable, assetItemInfo);

                            ClearCache();

                            if (redirect.Length < 1)
                            {
                                redirect = "AssetItemEntry.aspx?action=EDIT&assetItemID=" + Request.QueryString["assetItemID"].ToString();

                                string addScript = "location.href='" + redirect + "'";
                                this.Alert(this.GetMessage("SaveSuccessfully"), 10, addScript);
                            }
                            else
                            {
                                string addScript = "location.href='" + redirect + "'";
                                this.Alert(this.GetMessage("SaveSuccessfully"), 10, addScript);
                            }
                        }
                        else
                        {
                            Alert(GetMessage("SOM_ExistSameItem"));
                        }
                    }
                    else
                    {
                        Response.Redirect("AssetItemList.aspx");
                    }
                }
            }
        }

        #region Bind grid function.

        //Bind Detail grid.
        private void BindDetailList()
        {
            this.grdAssetItemDetail.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            DataTable detailTable = GetDataTable(BLL.COM.Session.SOM_grdDetail);

            DataView dvDetail = detailTable.DefaultView;
            dvDetail.RowFilter = this.chkShowVoid.Checked ? "" : "FlagObsolete=0";
            dvDetail.Sort = this.grdAssetItemDetail.DataViewSortExpression;
            this.grdAssetItemDetail.DataSource = dvDetail;
            this.grdAssetItemDetail.DataBind();

            detailTable.Dispose();
            detailTable = null;
        }

        //Bind history grid.
        private void BindHistoryList()
        {
            this.grdAssetItemHist.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            DataTable historyTable = GetDataTable(BLL.COM.Session.SOM_grdHist);

            DataView dvHistory = historyTable.DefaultView;
            dvHistory.RowFilter = "FlagObsolete=0";
            dvHistory.Sort = this.grdAssetItemHist.DataViewSortExpression;
            this.grdAssetItemHist.DataSource = dvHistory;
            this.grdAssetItemHist.DataBind();

            historyTable.Dispose();
            historyTable = null;
        }

        //Bind asset type list in detail grid.
        private void BindAssetTypeListInGrid(int editIndex)
        {
            int selectedStation = this.ddlStation.SelectedItem != null ? Convert.ToInt32(ddlStation.SelectedValue.ToString()) : 0;
            string stationIDs = "";
            SetStationSelectedItem(ref stationIDs, this.ddlStation);
            DropDownList assetType = (DropDownList)grdAssetItemDetail.Rows[editIndex].Cells[3].FindControl("ddlAssetTypeInGrid");
            //update by benson 2015-10-27 begin U264
            DataView dv = ODMS.DAL.SOM.CodeSetup.CDAssetType.GetAssetTypeList(stationIDs, "", true, this.LangCode).DefaultView;
            dv.Sort = "AssetTypeCode asc";
            BindListControl(assetType, "AssetTypeID", "AssetTypeCode", dv.ToTable(), false);
            //update by benson 2015-10-27 end
            FindByValueAndSelect(assetType, grdAssetItemDetail.DataKeys[editIndex]["AssetTypeID"].ToString());
        }

        //Bind asset item list in detail grid.
        private void BindAssetItemListInGrid(int editIndex)
        {
            DropDownList assetType = (DropDownList)grdAssetItemDetail.Rows[editIndex].Cells[3].FindControl("ddlAssetTypeInGrid");
            DropDownList assetItem = (DropDownList)grdAssetItemDetail.Rows[editIndex].Cells[4].FindControl("ddlAssetItemInDetailGrid");
            int iAssetType = assetType.SelectedItem != null ? Convert.ToInt32(assetType.SelectedValue) : -1;

            //DataTable tempDataSource = ODMS.DAL.SOM.CodeSetup.CDAssetItem.GetAssetItemList(0, "", iAssetType, "", "", true);

            //update by tim 20160307
            // DataTable tempDataSource = ODMS.DAL.SOM.CodeSetup.CDAssetItem.GetAssetItemList(0, "", iAssetType, "", "","", true);
            DataTable tempDataSource = ODMS.DAL.SOM.CodeSetup.CDAssetItem.GetAssetItemByAssetItemID(0, "", iAssetType, "", "", "", true);
            //end update

            for (int i = 0; i < tempDataSource.Rows.Count; i++)//Romove the parent item.
            {
                if (BLL.SOM.CodeSetup.AssetItem.IsParentItem(Convert.ToInt32(tempDataSource.Rows[i]["AssetItemID"])))
                {
                    tempDataSource.Rows.RemoveAt(i);
                }
                else if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "EDIT")
                {
                    if (Request.QueryString["assetItemID"] != null && Convert.ToInt32(Request.QueryString["assetItemID"]) == Convert.ToInt32(tempDataSource.Rows[i]["AssetItemID"]))
                    {
                        tempDataSource.Rows.RemoveAt(i);
                    }
                }
            }

            tempDataSource.AcceptChanges();
            //update by benson 2015-10-27 begin U264
            DataView dv = tempDataSource.DefaultView;
            dv.Sort = "AssetItemCode asc";
            BindListControl(assetItem, "AssetItemID", "AssetItemCode", dv.ToTable(), false);
            //update by benson 2015-10-27 end U264
            FindByValueAndSelect(assetItem, grdAssetItemDetail.DataKeys[editIndex]["SrcAssetItemID"].ToString());

            //if (assetItem.Items.FindByValue(grdAssetItemDetail.DataKeys[editIndex]["SrcAssetItemID"].ToString()) != null)
            //{
            //    assetItem.SelectedValue = grdAssetItemDetail.DataKeys[editIndex]["SrcAssetItemID"].ToString();
            //}

            tempDataSource.Dispose();
            tempDataSource = null;
        }
        #endregion

        /// <summary>
        /// Function Item Setting.
        /// </summary>
        private void FunctionItemSetting()
        {
            if (DAL.Security.User.CanFunctionItemAccess("M140803_F1", this.ODMUser.UserProfileID, this.MenuID))//ReadOnly
            {
                this.txtAssetItem.Enabled = false;
                this.txtDescription.Enabled = false;

                this.btnSave.Enabled = false;
                this.btnSaveNew.Enabled = false;
                this.btnSaveReturn.Enabled = false;
                this.btnVoid.Enabled = false;
                this.ddlStation.Enabled = false;
                this.ddlAssetType.Enabled = false;

                this.chkItemSet.Enabled = false;
                this.btnDetailNew.Enabled = false;
                this.btnHistNew.Enabled = false;
                this.grdAssetItemDetail.Columns[8].Visible = false;
                this.grdAssetItemDetail.Columns[9].Visible = false;
                this.grdAssetItemHist.Columns[6].Visible = false;
                this.grdAssetItemHist.Columns[7].Visible = false;
            }

            if (DAL.Security.User.CanFunctionItemAccess("M140803_F2", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {
                //update by gordon 20151020 U247 
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.StationID), false);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.LocationID), false);
            }
            else if (DAL.Security.User.CanFunctionItemAccess("M140803_F3", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {
                //BindStation
                //update by gordon 20151020 U247 
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), false);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), false);
            }
            else
            {
                //update by gordon 20151020 U247 
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), false);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), false);
                this.ddlStation.Enabled = false;
            }

            //update by gordon 20151020 U247 
            //if (ddlStation.Items.FindByValue(this.ODMUser.StationID.ToString()) != null)//selected current station.
            //{
            //    this.ddlStation.SelectedValue = this.ODMUser.StationID.ToString();
            //}
            if (ddlStation.Items.FindByValue(this.ODMUser.LocationID.ToString()) != null)//selected current station.
            {
                this.ddlStation.SelectedValue = this.ODMUser.LocationID.ToString();
            }
        }

        /// <summary>
        /// If this record is voided set control is readonly.
        /// </summary>
        private void VoidSetWhenDisplay()
        {
            this.btnSave.Enabled = false;
            this.btnSaveNew.Enabled = false;
            this.btnSaveReturn.Enabled = false;
            this.btnVoid.Enabled = false;
            this.btnDetailNew.Enabled = false;
            this.btnHistNew.Enabled = false;
            this.chkItemSet.Enabled = false;
            this.txtDescription.Enabled = false;
            this.txtAssetItem.Enabled = false;
            this.ddlAssetType.Enabled = false;
            this.ddlStation.Enabled = false;

            this.grdAssetItemDetail.Columns[8].Visible = false;
            this.grdAssetItemDetail.Columns[9].Visible = false;
            this.grdAssetItemHist.Columns[6].Visible = false;
            this.grdAssetItemHist.Columns[7].Visible = false;

        }

        #endregion

        #region SetLanguage

        void AssetItemEntry_ChangeLanguage(object sender, EventArgs e)
        {
            SetLanguage();
            Display();
        }

        private void SetLanguage()
        {
            this.lblMenuCaption.Text = GetLabel("SOM_AssetItemEntry");
            this.lblStation.Text = GetLabel("SOM_Station", true);
            this.lblAssetType.Text = GetLabel("SOM_AssetType", true);
            this.lblAssetItem.Text = GetLabel("SOM_AssetItem", true);
            this.lblObsolete.Text = GetLabel("SOM_Void", true);
            this.lblStockQty.Text = GetLabel("SOM_StockQty", true);
            this.lblAvailableQty.Text = GetLabel("SOM_AvailableQty", true);
            this.lblDescription.Text = GetLabel("COM_Description", true);
            this.lblAssetItemEntryDetail.Text = GetLabel("SOM_AssetItemEntryDetail", true);
            this.lblAssetItemHistory.Text = GetLabel("SOM_AssetItemHistory", true);

            this.btnDetailNew.Text = GetLabel("COM_CreateNew");
            this.btnSaveReturn.Text = GetLabel("COM_SaveAndReturn");
            this.btnSaveNew.Text = GetLabel("SOM_SaveNew");
            this.btnVoid.Text = GetLabel("SOM_VoidOperation");
            this.btnSave.Text = GetLabel("COM_Save");
            this.btnCancel.Text = GetLabel("COM_Cancel");
            this.btnHistNew.Text = GetLabel("COM_CreateNew");
            this.lblItemSet.Text = GetLabel("SOM_ThisIsAnItemSet");
            this.lblShowVoid.Text = GetLabel("COM_Show", true);
            this.chkShowVoid.Text = GetLabel("SOM_Voided");
            /* Comment by jack 20151023 for U252 */
            this.btnClearAssetType.Text = GetLabel("SOM_ClearAssetType");
        }

        #endregion

        #region Grid Event

        #region Detail Grid Event.

        //row edit.
        protected void grdAssetItemDetail_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.grdAssetItemDetail.EditIndex = e.NewEditIndex;
            BindDetailList();

            Button btnShowDetail = (Button)grdAssetItemDetail.Rows[e.NewEditIndex].Cells[4].FindControl("btnDtlShowDetail");
            if (btnShowDetail != null)
            {
                btnShowDetail.Visible = false;
            }

            BindAssetTypeListInGrid(e.NewEditIndex);
            BindAssetItemListInGrid(e.NewEditIndex);

            //set description.
            Label tempDecription = (Label)grdAssetItemDetail.Rows[e.NewEditIndex].Cells[5].FindControl("lblDetailDescription");
          
            DropDownList srcItemCode = (DropDownList)grdAssetItemDetail.Rows[e.NewEditIndex].Cells[4].FindControl("ddlAssetItemInDetailGrid");
            if (tempDecription != null)
            {
                if (srcItemCode.SelectedItem != null)
                {
                    tempDecription.Text = srcItemCode.SelectedItem.Text;
                }
            }
        }

        //asset type selected changed.
        protected void ddlAssetTypeInGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            int editIndex = this.grdAssetItemDetail.EditIndex;

            BindAssetItemListInGrid(editIndex);

            Label tempDecription = (Label)grdAssetItemDetail.Rows[editIndex].Cells[5].FindControl("lblDetailDescription");
            DropDownList srcItemCode = (DropDownList)grdAssetItemDetail.Rows[editIndex].Cells[4].FindControl("ddlAssetItemInDetailGrid");
            if (tempDecription != null)//set item descritpion.
            {
                if (srcItemCode.SelectedItem != null)
                {
                    tempDecription.Text = BLL.SOM.CodeSetup.AssetItem.GetAssetItemInfoByID(int.Parse(srcItemCode.SelectedItem.Value)).AssetItemDesc;
                }
                else
                {
                    tempDecription.Text = "";
                }
            }
        }

        //asset Items selected changed set description.
        protected void ddlAssetItemInGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            int editIndex = this.grdAssetItemDetail.EditIndex;

            Label tempDecription = (Label)grdAssetItemDetail.Rows[editIndex].Cells[5].FindControl("lblDetailDescription");
            DropDownList srcItemCode = (DropDownList)sender;
            if (tempDecription != null)//set item descritpion.
            {
                if (srcItemCode.SelectedItem != null)
                {
                    tempDecription.Text = BLL.SOM.CodeSetup.AssetItem.GetAssetItemInfoByID(int.Parse(srcItemCode.SelectedItem.Value)).AssetItemDesc;
                }
                else
                {
                    tempDecription.Text = "";
                }
            }
        }

        //row update.
        protected void grdAssetItemDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int editIndex = grdAssetItemDetail.EditIndex;
            DropDownList assetType = (DropDownList)grdAssetItemDetail.Rows[editIndex].Cells[3].FindControl("ddlAssetTypeInGrid");
            DropDownList srcItemCode = (DropDownList)grdAssetItemDetail.Rows[editIndex].Cells[4].FindControl("ddlAssetItemInDetailGrid");
            Label tempDecription = (Label)grdAssetItemDetail.Rows[editIndex].Cells[5].FindControl("lblDetailDescription");
            TextBox tempQty = (TextBox)grdAssetItemDetail.Rows[editIndex].Cells[6].FindControl("txtSOM_Qty");
            CheckBox tempObsolete = (CheckBox)grdAssetItemDetail.Rows[editIndex].Cells[7].Controls[0];

        
            //Check input data to cache.
            if (assetType.SelectedItem != null && srcItemCode.SelectedItem != null && tempQty.Text.Trim().Length > 0)
            {
                string srcItem = srcItemCode.SelectedValue.Length > 0 ? srcItemCode.SelectedValue : "-1";
                string strAssetType = assetType.SelectedValue.Length > 0 ? assetType.SelectedValue : "-1";
                string strQty = tempQty.Text.Length > 0 ? tempQty.Text : "0";
               
                int tempStockQty = this.txtStockQty.Text.Length > 0 ? Convert.ToInt32(this.txtStockQty.Text) : 0;
                int sumQty = Convert.ToInt32(strQty) * tempStockQty;
                //modify by tim 20160512 for save qty before modify
               
                int subItemQty = MTRC.ODMS.DAL.SOM.CodeSetup.CDAssetItem.GetAvailableQtyByID(Convert.ToInt32(srcItem));
                int tempAssetItemID = 0;
                if (Request.QueryString["assetItemID"] != null)
                {
                    tempAssetItemID = Convert.ToInt32(Request.QueryString["assetItemID"]);
                }

                int BeforeQty = MTRC.ODMS.DAL.SOM.CodeSetup.CDAssetItem.GetCDAssetItemQty(tempAssetItemID, Convert.ToInt32(srcItem));

                if (BeforeQty != 0)
                {
                    subItemQty += BeforeQty * tempStockQty;
                }
               // subItemQty += beforeQty;
                //end by modify
              

                if (!CheckDetailRepertItems(Convert.ToInt32(grdAssetItemDetail.DataKeys[editIndex]["AssetItemDtlID"].ToString()), Convert.ToInt32(strAssetType), Convert.ToInt32(srcItem)))
                {
                    //U43 Edward 20150811
                    if (subItemQty > 0 && (subItemQty >= sumQty)) //if (subItemQty > 0 && (subItemQty > sumQty)) Modified by Edward 20150930 for U43
                    {

                        DataTable dt = GetDataTable(BLL.COM.Session.SOM_grdDetail);

                        if (dt.Select("AssetItemDtlID=" + grdAssetItemDetail.DataKeys[editIndex]["AssetItemDtlID"].ToString()).Length < 1)
                        {
                            DataRow newRow = dt.NewRow();
                            newRow["AssetItemDtlID"] = grdAssetItemDetail.DataKeys[editIndex]["AssetItemDtlID"];
                            dt.Rows.Add(newRow);
                        }

                        DataRow dr = dt.Select("AssetItemDtlID=" + grdAssetItemDetail.DataKeys[editIndex]["AssetItemDtlID"].ToString())[0];

                        dr["SrcAssetItemID"] = srcItem.Length > 0 ? Convert.ToInt32(srcItem) : -1;
                        dr["AssetTypeID"] = strAssetType.Length > 0 ? Convert.ToInt32(strAssetType) : -1;
                        dr["AssetType"] = assetType.SelectedItem.Text;
                        dr["AssetItemDetail"] = srcItemCode.SelectedItem.Text;
                        dr["Sequence"] = GetColumnMaxValue(dt, "Sequence");
                        dr["Description"] = tempDecription.Text;
                        dr["Qty"] = Convert.ToInt32(tempQty.Text);
                        dr["FlagObsolete"] = tempObsolete.Checked;

                        CacheTempData(dt, BLL.COM.Session.SOM_grdDetail);

                        this.grdAssetItemDetail.EditIndex = -1;
                        this.BindDetailList();

                        dt.Dispose();
                        dt = null;
                    }
                    else
                    {
                        PAlert(GetMessage("SOM_AssetItemsQtyDeficit", this.LangCode));
                    }

                }
                else
                {
                    PAlert(GetMessage("SOM_ExistSameItem"));
                }
            }
            else
            {
                if (assetType.SelectedItem == null)
                {
                    PAlert(this.GetLabel("SOM_AssetType") + " " + GetMessage("SOM_NotIsEmpty"));//Modified by ZBH 2011-12-30 QC464
                }
                else if (srcItemCode.SelectedItem == null)
                {
                    PAlert(this.GetLabel("SOM_AssetItem") + " " + GetMessage("SOM_NotIsEmpty"));//Modified by ZBH 2011-12-30 QC464
                }
                else if (tempQty.Text.Trim().Length < 1)
                {
                    PAlert(this.GetLabel("SOM_Qty") + " " + GetMessage("SOM_NotIsEmpty"));//Modified by ZBH 2011-12-30 QC464
                }
                else
                {
                    PAlert(GetMessage("SOM_MandatoryItemNotNull"));
                }

            }

        }

        //Row cancel
        protected void grdAssetItemDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.grdAssetItemDetail.EditIndex = -1;
            this.BindDetailList();
        }

        //Rebind.
        protected void grdAssetItemDetail_NeedDataBind()
        {
            BindDetailList();
        }

        //Search.
        protected void chkShowVoid_CheckedChanged(object sender, EventArgs e)
        {
            BindDetailList();
        }

        //New row.
        protected void btnDetailNew_Click(object sender, EventArgs e)
        {

            //string tempName = "Qty0"  + ODMUserID;
            //Session[tempName] = null;

            //Add new a row.
            DataTable detailTable = GetDataTable(BLL.COM.Session.SOM_grdDetail);
            DataRow newRow = detailTable.NewRow();
            newRow["AssetItemDtlID"] = GetColumnMinValue(detailTable, "AssetItemDtlID");
            newRow["Sequence"] = GetColumnMaxValue(detailTable, "Sequence");
            newRow["FlagObsolete"] = 0;
            detailTable.Rows.InsertAt(newRow, 0);

            //bind grid.
            DataView dvTemp = detailTable.DefaultView;

            if (!this.chkShowVoid.Checked)//includ void?
            {
                dvTemp.RowFilter = "FlagObsolete=0";
            }

            dvTemp.Sort = grdAssetItemDetail.DataViewSortExpression;
            grdAssetItemDetail.EditIndex = 0;
            grdAssetItemDetail.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            grdAssetItemDetail.DataSource = dvTemp;
            grdAssetItemDetail.DataBind();

            BindAssetTypeListInGrid(0);
            BindAssetItemListInGrid(0);

            Button btnShowDetail = (Button)grdAssetItemDetail.Rows[grdAssetItemDetail.EditIndex].Cells[4].FindControl("btnDtlShowDetail");
            if (btnShowDetail != null)
            {
                btnShowDetail.Visible = false;
            }

            this.ddlStation.Enabled = false;

            detailTable.Dispose();
            detailTable = null;
            //Cache data.
            //CacheTempData(detailTable, BLL.COM.Session.SOM_grdDetail);
        }

        protected void chkItemSet_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkItemSet.Checked)
            {
                this.btnDetailNew.Enabled = true;
                this.chkItemSet.Enabled = false;
            }
        }

        //RowBound
        protected void grdAssetItemDetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.Header)
            //{
            //    //((APJ.Web.UI.WebControls.DateTextBox)(e.Row.Cells[1].FindControl("dtbGrvEventEventTime")))
            //    //lblSeqEventTime.Text = this.GetLabel("SOM_GeneralEventTime", false);
            //    //this.lblSeqlMustInput.Text = "<EM>*</EM>";
            //    ((Label)(e.Row.Cells[0].FindControl("lblAssetTypeHeaderInGrid"))).Text = this.GetLabel("SOM_AssetType", false);
            //}
            if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != this.grdAssetItemDetail.EditIndex)
            {
                Button tempButton = (Button)(e.Row.Cells[4].FindControl("btnDtlShowDetail"));
                tempButton.Visible = false;
                tempButton.Attributes.Add("onclick", "javascript:ShowDetails(" + ((Label)(e.Row.Cells[4].FindControl("lblCOM_Description"))).ClientID.ToString() + "); return false;");
                tempButton.Visible = true;

                if (((Label)(e.Row.Cells[4].FindControl("lblDetailDescription"))).Text.Trim().Length >= DetailLength)
                {
                    // edit by dylan 20151019 for u241
                    //((Label)(e.Row.Cells[4].FindControl("lblDetailDescription"))).Text = ((Label)(e.Row.Cells[4].FindControl("lblDetailDescription"))).Text.Substring(0, 10);
                    ((Label)(e.Row.Cells[4].FindControl("lblDetailDescription"))).Text = ((Label)(e.Row.Cells[4].FindControl("lblDetailDescription"))).Text.Substring(0, DetailLength);
                }

                ImageButton btnRowVoid = (ImageButton)e.Row.Cells[9].FindControl("imgDtlVoid");
                if (btnRowVoid != null)
                {
                    btnRowVoid.CommandArgument = e.Row.RowIndex.ToString();
                    btnRowVoid.Attributes.Add("onclick", "return confirm('" + GetMessage("COM_ConfirmSubmit") + "');");
                }

                if (Convert.ToBoolean(this.grdAssetItemDetail.DataKeys[e.Row.RowIndex]["FlagObsolete"]))
                {
                    e.Row.Cells[8].FindControl("imgDtlEdit").Visible = false;
                    e.Row.Cells[9].FindControl("imgDtlVoid").Visible = false;
                }
            }
        }

        //Void
        protected void grdAssetItemDetail_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            this.AjaxUpdateIsServerChanged();

            int editIndex = 0;
            int.TryParse(e.CommandArgument.ToString(), out editIndex);

            if (e.CommandName == "Void")
            {
                if (editIndex == grdAssetItemDetail.EditIndex)
                {
                    DataTable dt = GetDataTable(BLL.COM.Session.SOM_grdDetail);

                    if (dt.Select("AssetItemDtlID=" + grdAssetItemDetail.DataKeys[editIndex]["AssetItemDtlID"]).Length > 0)//current row a new?
                    {
                        DataRow tempRow = dt.Select("AssetItemDtlID=" + grdAssetItemDetail.DataKeys[editIndex]["AssetItemDtlID"])[0];
                        tempRow["FlagObsolete"] = 1;
                        CacheTempData(dt, BLL.COM.Session.SOM_grdDetail);
                    }

                    this.grdAssetItemDetail.EditIndex = -1;
                    BindDetailList();

                    dt.Dispose();
                    dt = null;
                }
                else
                {
                    DataTable dt = GetDataTable(BLL.COM.Session.SOM_grdDetail);

                    if (dt.Select("AssetItemDtlID=" + grdAssetItemDetail.DataKeys[editIndex]["AssetItemDtlID"]).Length > 0)//current row a new?
                    {
                        DataRow tempRow = dt.Select("AssetItemDtlID=" + grdAssetItemDetail.DataKeys[editIndex]["AssetItemDtlID"])[0];
                        tempRow["FlagObsolete"] = 1;
                        CacheTempData(dt, BLL.COM.Session.SOM_grdDetail);
                    }

                    BindDetailList();

                    dt.Dispose();
                    dt = null;
                }
            }
        }

        #endregion

        #region Hist Grid Event.

        //rebind.
        protected void grdAssetItemHist_NeedDataBind()
        {
            BindHistoryList();
        }

        //row bound set TransactionDate and void Values.
        protected void grdAssetItemHist_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //format datetime
            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow && e.Row.Cells[2].Text.Trim().Length > 8)
            {
                e.Row.Cells[2].Text = this.FormatDateTime(e.Row.Cells[2].Text, true);
            }

            if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != grdAssetItemHist.EditIndex)
            {
                Button tempButton = (Button)(e.Row.Cells[4].FindControl("btnHistShowDetail"));
                tempButton.Visible = false;
                tempButton.Attributes.Add("onclick", "javascript:ShowDetails(" + ((Label)(e.Row.Cells[4].FindControl("lblHistRemarks"))).ClientID.ToString() + "); return false;");

                tempButton.Visible = true;
                if (((Label)(e.Row.Cells[4].FindControl("lblShowHistRemarks"))).Text.Trim().Length >= DetailLength)
                {
                    // edit by dylan 20151019 for u241
                    //((Label)(e.Row.Cells[4].FindControl("lblShowHistRemarks"))).Text = ((Label)(e.Row.Cells[4].FindControl("lblShowHistRemarks"))).Text.Substring(0, 10);
                    ((Label)(e.Row.Cells[4].FindControl("lblShowHistRemarks"))).Text = ((Label)(e.Row.Cells[4].FindControl("lblShowHistRemarks"))).Text.Substring(0, DetailLength);
                }

                this.grdAssetItemHist.Columns[6].Visible = false;//hidden edit column.
            }

            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
            {
                DateTime dateTime = this.ConvertToDateTime(grdAssetItemHist.DataKeys[e.Row.RowIndex]["TransactionDate"].ToString());
                APJ.Web.UI.WebControls.DateTextBox tempDateTextBox = (APJ.Web.UI.WebControls.DateTextBox)e.Row.Cells[2].FindControl("txtTransactionDate");
                if (tempDateTextBox != null)
                    tempDateTextBox.SetDateTime(dateTime);

                CheckBox tempVoid = (CheckBox)e.Row.Cells[5].Controls[0];
                if (tempVoid != null)
                {
                    if (grdAssetItemHist.EditIndex < 0)
                    {
                        tempVoid.Enabled = false;
                    }
                    else
                    {
                        tempVoid.Enabled = Convert.ToInt32(grdAssetItemHist.DataKeys[e.Row.RowIndex]["AssetItemDtlHistID"]) > 0 ? false : true;
                    }
                }

                ImageButton btnRowEdit = (ImageButton)e.Row.Cells[6].FindControl("btnRowEdit");
                if (btnRowEdit != null)
                {
                    btnRowEdit.CommandArgument = e.Row.RowIndex.ToString();
                }

                ImageButton btnRowUpdate = (ImageButton)e.Row.Cells[6].FindControl("btnRowUpdate");
                if (btnRowUpdate != null)
                {
                    btnRowUpdate.CommandArgument = e.Row.RowIndex.ToString();
                }

                ImageButton btnRowVoid = (ImageButton)e.Row.Cells[7].FindControl("imgHistVoid");
                if (btnRowVoid != null)
                {
                    btnRowVoid.Attributes.Add("onclick", "return confirm('" + GetMessage("COM_ConfirmSubmit") + "');");
                    btnRowVoid.CommandArgument = e.Row.RowIndex.ToString();
                }
            }
        }

        //row edit.
        protected void grdAssetItemHist_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.grdAssetItemHist.EditIndex = e.NewEditIndex;
            BindHistoryList();
        }

        //row cancel.
        protected void grdAssetItemHist_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.grdAssetItemHist.EditIndex = -1;

            BindHistoryList();
        }

        //add new row.
        protected void btnHistNew_Click(object sender, EventArgs e)
        {
            DataTable histTable = GetDataTable(BLL.COM.Session.SOM_grdHist);
            DataRow newRow = histTable.NewRow();
            newRow["AssetItemDtlHistID"] = GetColumnMinValue(histTable, "AssetItemDtlHistID");
            newRow["TransactionDate"] = DateTime.Now;
            newRow["sequence"] = GetColumnMaxValue(histTable, "sequence");
            newRow["FlagObsolete"] = 0;

            if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "EDIT")
            {
                if (Request.QueryString["assetItemID"] != null)
                {
                    newRow["AssetItemID"] = Convert.ToInt32(Request.QueryString["assetItemID"]);
                }
                else
                {
                    Response.Redirect("AssetItemList.aspx");
                }
            }
            else if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "NEW")
            {
                newRow["AssetItemID"] = 0;
            }
            else
            {
                Response.Redirect("AssetItemList.aspx");
            }

            histTable.Rows.InsertAt(newRow, 0);

            DataView dvTemp = histTable.DefaultView;
            dvTemp.Sort = grdAssetItemHist.DataViewSortExpression;
            grdAssetItemHist.EditIndex = 0;
            grdAssetItemHist.DataSource = dvTemp;
            dvTemp.RowFilter = "FlagObsolete=0";
            grdAssetItemHist.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            grdAssetItemHist.DataBind();

            this.grdAssetItemHist.Columns[6].Visible = true;//shown edit column.

            histTable.Dispose();
            histTable = null;
            //CacheTempData(histTable, BLL.COM.Session.SOM_grdHist);
        }

        //row edit ,row update.
        protected void grdAssetItemHist_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            this.AjaxUpdateIsServerChanged();

            int editIndex = 0;
            int.TryParse(e.CommandArgument.ToString(), out editIndex);

            if (e.CommandName == "RowEdit")//edit
            {
                this.grdAssetItemHist.EditIndex = editIndex;
                BindHistoryList();
            }
            else if (e.CommandName == "RowUpdate")//update
            {
                DataTable dt = GetDataTable(BLL.COM.Session.SOM_grdHist);
                APJ.Web.UI.WebControls.DateTextBox tempTransactionDate = (APJ.Web.UI.WebControls.DateTextBox)grdAssetItemHist.Rows[editIndex].Cells[2].FindControl("txtTransactionDate");
                TextBox txtQtyChg = (TextBox)grdAssetItemHist.Rows[editIndex].Cells[3].FindControl("txtQtyChg");
                TextBox txtRemarks = (TextBox)grdAssetItemHist.Rows[editIndex].Cells[4].FindControl("txtHistRemarks");
                CheckBox tempObsolete = (CheckBox)grdAssetItemHist.Rows[editIndex].Cells[5].Controls[0];

                if (tempTransactionDate.Text.Length > 2 && txtQtyChg.Text.Length > 0 && txtRemarks.Text.Length > 0)
                {
                    if (tempTransactionDate.GetDateTime() > MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime())
                    {
                        PAlert(this.GetMessage("SOM_AssetItemEntryHistDateCheck"));
                        return;
                    }

                    //Add by jack 20160129 for ISU35
                    CalculateStockQtyAndAvailableQty();
                    if (Convert.ToInt32(txtQtyChg.Text) < 0 && (Convert.ToInt32(txtQtyChg.Text)+Convert.ToInt32(txtAvailableQty.Text)) < 0)
                    {
                        PAlert(this.GetMessage("SOM_CodeSetup_AseetLoan_NotEnoughTolend"));
                        return;
                    }
                    //End add by jack 20160129 for ISU35

                    if (dt.Select("AssetItemDtlHistID=" + grdAssetItemHist.DataKeys[editIndex]["AssetItemDtlHistID"]).Length < 1)
                    {
                        DataRow newRow = dt.NewRow();
                        newRow["AssetItemDtlHistID"] = grdAssetItemHist.DataKeys[editIndex]["AssetItemDtlHistID"];
                        dt.Rows.Add(newRow);
                    }

                    this.grdAssetItemHist.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);

                    DataRow dr = dt.Select("AssetItemDtlHistID=" + grdAssetItemHist.DataKeys[editIndex]["AssetItemDtlHistID"])[0];
                    dr["TransactionDate"] = tempTransactionDate.GetDateTime();
                    dr["QtyChg"] = txtQtyChg.Text.Length > 0 ? Convert.ToInt32(txtQtyChg.Text) : 0;
                    dr["Remarks"] = txtRemarks.Text;
                    dr["FlagObsolete"] = tempObsolete.Checked;
                    dr["sequence"] = GetColumnMaxValue(dt, "sequence");
                    DataView tempView = dt.DefaultView;
                    this.grdAssetItemHist.DataSource = tempView;
                    tempView.RowFilter = "FlagObsolete=0";
                    tempView.Sort = this.grdAssetItemHist.SortExpression;
                    this.grdAssetItemHist.EditIndex = -1;
                    this.grdAssetItemHist.DataBind();

                    CacheTempData(dt, BLL.COM.Session.SOM_grdHist);

                    CalculateStockQtyAndAvailableQty();

                    this.grdAssetItemHist.Columns[6].Visible = false;//hidden edit column.
                }
                else
                {
                    if (tempTransactionDate.Text.Length < 1)
                    {
                        PAlert(this.GetLabel("SOM_TransactionDate") + " " + GetMessage("SOM_NotIsEmpty"));//Modified by ZBH 2011-12-30 QC464
                    }
                    else if (txtQtyChg.Text.Length < 1)
                    {
                        PAlert(this.GetLabel("SOM_ChangeInQuantity") + " " + GetMessage("SOM_NotIsEmpty"));//Modified by ZBH 2011-12-30 QC464
                    }
                    else if (txtRemarks.Text.Length < 1)
                    {
                        PAlert(this.GetLabel("COM_Remark") + " " + GetMessage("SOM_NotIsEmpty"));//Modified by ZBH 2011-12-30 QC464
                    }
                    else
                    {
                        PAlert(GetMessage("SOM_MandatoryItemNotNull"));
                    }
                }

                dt.Dispose();
                dt = null;
            }
            else if (e.CommandName == "RowCancel")
            {
                this.grdAssetItemHist.EditIndex = -1;
                BindHistoryList();

                this.grdAssetItemHist.Columns[6].Visible = false;//hidden edit column.
            }
            else if (e.CommandName == "Void")
            {
                if (grdAssetItemHist.EditIndex == editIndex)//Current edit row.
                {
                    DataTable dt = GetDataTable(BLL.COM.Session.SOM_grdHist);

                    if (dt.Select("AssetItemDtlHistID=" + grdAssetItemHist.DataKeys[editIndex]["AssetItemDtlHistID"]).Length > 0)//current row a new?
                    {
                        DataRow tempRow = dt.Select("AssetItemDtlHistID=" + grdAssetItemHist.DataKeys[editIndex]["AssetItemDtlHistID"])[0];
                        tempRow["FlagObsolete"] = 1;
                        CacheTempData(dt, BLL.COM.Session.SOM_grdHist);
                    }

                    this.grdAssetItemHist.EditIndex = -1;
                    BindHistoryList();

                    dt.Dispose();
                    dt = null;
                }
                else
                {
                    DataTable dt = GetDataTable(BLL.COM.Session.SOM_grdHist);

                    if (dt.Select("AssetItemDtlHistID=" + grdAssetItemHist.DataKeys[editIndex]["AssetItemDtlHistID"]).Length > 0)//current row a new?
                    {
                        DataRow tempRow = dt.Select("AssetItemDtlHistID=" + grdAssetItemHist.DataKeys[editIndex]["AssetItemDtlHistID"])[0];
                        tempRow["FlagObsolete"] = 1;
                        CacheTempData(dt, BLL.COM.Session.SOM_grdHist);
                    }

                    BindHistoryList();

                    dt.Dispose();
                    dt = null;
                }

                CalculateStockQtyAndAvailableQty();
            }
        }

        #endregion

        #endregion

        #region Menu Event.

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveFunction("");
            Session["Ismodify"] = false;
            Session["Index"] = null;

            //save.
        }

        protected void btnSaveNew_Click(object sender, EventArgs e)
        {
            string redirectUrl = "AssetItemEntry.aspx?action=NEW";
            SaveFunction(redirectUrl);
            Session["Ismodify"] = false;
            Session["Index"] = null;
            //save and new.
        }

        protected void btnVoid_Click(object sender, EventArgs e)
        {
            //Check Can Void?
            if (Request.QueryString["action"] != null && Request.QueryString["action"].ToUpper() == "EDIT" && Request.QueryString["assetItemID"] != null)
            {
                int assetItemID = Convert.ToInt32(Request.QueryString["assetItemID"]);

                //if (DAL.SOM.CodeSetup.CDAssetItem.CheckCanVoid(assetItemID))//COM_ConfirmSubmit
                //{
                //delete
                //modify by tim 20160409 for save stockqty
                int stockQty = 0;
                int.TryParse(this.txtStockQty.Text, out stockQty);
                BLL.SOM.CodeSetup.AssetItem.DeleteAssetItem(assetItemID, this.ODMUser.ID, stockQty);
                // modify add
                Response.Redirect("AssetItemEntry.aspx?action=Edit&assetItemID=" + assetItemID);
                //}
                //else
                //{
                //    Alert(GetMessage("SOM_CanNotVoid"));//This asset item can not void.
                //}
            }
            else
            {
                ClearCache();

                Response.Redirect("AssetItemList.aspx");
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            //cancel
            ClearCache();
            Response.Redirect("AssetItemList.aspx");
        }

        protected void btnSaveReturn_Click(object sender, EventArgs e)
        {
            string redirectUrl = "AssetItemList.aspx";
            SaveFunction(redirectUrl);
            Session["Ismodify"] = false;
            Session["Index"] = null;
            //save and return.
        }

        /*Comment by jack 20151023 for U252*/
        protected void btnClearAssetType_Click(object sender, EventArgs e)
        {
            BindAssetType();
        }

        #endregion

        #region Other Event

        protected void ddlStation_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindAssetType();
        }

        #endregion

    }
}
